<template>
  <div
    v-if="dialogTableVisible1"
    :fullscreen="false"
    :modal="false"
    :show-close="false"
    :width="screenWidth + 20 + 'px'"
    :append-to-body="true"
    style="
      position: absolute;
      left: 6rem;
      margin-top: 42px;
      z-index: 10;
      background-color: white;
    "
    :close-on-click-modal="false"
  >
    <div :style="{ width: screenWidth - 96 + 'px' }">
      <div
        :style="{
          height: '40px',
          borderBottom: '1px solid #ccc',
          width: '100%',
        }"
      >
        <div style="position: absolute; right: 15px">
          <el-button @click="flushed" type="primary"> 刷新</el-button>
          <!-- <el-button v-if="Permission" @click="upButton" type="primary">
        修改业务员</el-button
      > -->
          <!-- <el-button @click="addRow" type="primary">增行</el-button> -->
          <!-- <el-button @click="deleteSelectedRows" type="danger">删除</el-button> -->
          <el-button
            type="primary"
            @click="getAllData(ruleFormRef)"
            v-if="showInsertButton"
            >保存</el-button
          >
          <el-button
            type="primary"
            @click="updateMaterialsFixed(ruleFormRef)"
            v-if="!showInsertButton"
            >保存</el-button
          >

          <el-button @click="OFFdialogTableVisible" type="danger">关闭</el-button>
        </div>
      </div>
    </div>

    <div
      ref="titleDiv"
      :style="{
        backgroundColor: 'rgba(247, 247, 247, 0.903)',
        height: 130 + 'px',
        width: screenWidth - 96 + 'px',
      }"
    >
      <el-form :model="formMainTable" :inline="true">
        <!-- <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">更换标准编号</label>
          <el-input
            style="width: 180px"
            v-model="formMainTable.processCode"
            placeholder="自动生成"
            disabled
            clearable
          />
        </el-form-item>
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px"
            ><span style="color: red; font-weight: 700">*</span>更换标准名称</label
          >
          <el-input style="width: 180px" v-model="formMainTable.processName" clearable />
        </el-form-item> -->
        <el-form :model="formMainTable" :inline="true">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              <span style="color: red; font-weight: 700">*</span>用途分类</label
            >
            <el-input
              style="width: 180px"
              v-model="formMainTable.productPurposeName"
              :readonly="true"
              @click="openEqipmentParts1()"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              <span style="color: red; font-weight: 700">*</span>材质:</label
            >
            <el-input
              style="width: 180px"
              v-model="formMainTable.materialName"
              :readonly="true"
              @click="openEqipmentParts2()"
              clearable
            />
          </el-form-item>
          <!-- procedures -->
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 工序</label>
            <el-select
              v-model="formMainTable.procedures"
              style="width: 180px"
              :readonly="true"
            >
              <el-option label="轧机" value="0"></el-option>
              <el-option label="退火" value="1"></el-option>
              <el-option label="拉矫" value="2"></el-option>
              <el-option label="分条" value="3"></el-option>
              <el-option label="清洗线" value="4"></el-option>
              <el-option label="破带" value="5"></el-option>
              <el-option label="大分条" value="6"></el-option>
              <el-option label="去应力" value="7"></el-option>
              <el-option label="贴膜" value="8"></el-option>
              <el-option label="研磨" value="9"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 工序类别</label>
            <el-select
              v-model="formMainTable.processProperty"
              style="width: 180px"
              :readonly="true"
              @change="openprocessProperty()"
            >
              <!-- <el-option label="——————" value="0"></el-option> -->
              <el-option label="成品" value="1"></el-option>
              <el-option label="半成品" value="2"></el-option>
              <!-- <el-option label="分条成品" value="3"></el-option>
                <el-option label="分条半成品" value="4"></el-option> -->
              <el-option label="成品,半成品" value="5"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-form :model="formMainTable" :inline="true">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              <span style="color: red; font-weight: 700">*</span> 设备结构</label
            >
            <el-input
              style="width: 180px"
              v-model="formMainTable.structureName"
              :readonly="true"
              @click="openEqipmentParts()"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              <span style="color: red; font-weight: 700">*</span> 辊轴类别</label
            >
            <el-input
              style="width: 180px"
              v-model="formMainTable.name"
              :readonly="true"
              @click="openEqipmentParts()"
              clearable
            />
          </el-form-item>

          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              <span style="color: red; font-weight: 700">*</span>型号</label
            >
            <el-input
              style="width: 180px"
              v-model="formMainTable.modelName"
              :readonly="true"
              @click="openEqipmentParts()"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 道次总数</label>
            <el-input
              style="width: 180px"
              v-model="formMainTable.passToolNumber"
              @blur="handleInput('passToolNumber')"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              <span style="color: red; font-weight: 700">*</span> 耗材类别</label
            >
            <el-input
              style="width: 180px"
              v-model="formMainTable.consumableCategoryName"
              :readonly="true"
              @click="openEqipmentParts()"
              clearable
            />
          </el-form-item> -->
        </el-form>
        <el-form :inline="true" :model="formMainTable">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              <el-checkbox
                @change="handleCheckBox1()"
                v-model="formMainTable.checkbox1"
              ></el-checkbox>

              硬度下限</label
            >
            <el-input
              style="width: 180px"
              v-model="formMainTable.lowerHardness"
              @blur="handleInput1('lowerHardness')"
              clearable
              :disabled="!formMainTable.checkbox1"
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 硬度上限</label>
            <el-input
              style="width: 180px"
              v-model="formMainTable.upHardness"
              @blur="handleInput1('upHardness')"
              clearable
              :disabled="!formMainTable.checkbox1"
            />
          </el-form-item>

          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              <el-checkbox
                @change="handleCheckBox2()"
                v-model="formMainTable.checkbox2"
              ></el-checkbox>
              版型下限</label
            >
            <el-input
              style="width: 180px"
              v-model="formMainTable.lowerPattern"
              @blur="handleInput1('lowerPattern')"
              clearable
              :disabled="!formMainTable.checkbox2"
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 版型上限</label>
            <el-input
              style="width: 180px"
              v-model="formMainTable.upPattern"
              @blur="handleInput1('upPattern')"
              clearable
              :disabled="!formMainTable.checkbox2"
            />
          </el-form-item>
        </el-form>
        <el-form :inline="true" :model="formMainTable">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 说明</label>
            <el-input style="width: 1040px" v-model="formMainTable.explain" clearable />
          </el-form-item>
        </el-form>
      </el-form>
    </div>

    <el-table
      ref="multipleTableRef"
      :data="tableData1"
      stripe
      border
      :row-style="{ height: '20px' }"
      :height="childTableHeight + 'px'"
      style="width: 100%"
      :max-height="childTableHeight + 'px'"
      :cell-style="cellStyle1"
      @selection-change="handleSelectionChange1"
      :header-cell-style="headerCellStyle1"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- 道次序号 -->
      <el-table-column :label="columnLabel" width="80" align="center">
        <template #default="{ $index }">
          <span>{{ $index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="道次名称" width="100" align="center">
        <template #default="{ row, $index }">
          <div style="height: 25px; line-height: 25px; cursor: pointer">
            {{ getPassName($index, formMainTable.passToolNumber) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用辊粗糙度" width="240" align="center">
        <el-table-column label="标准" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
              <span style="color: red; font-weight: 700">*</span>
            </span>
          </template>
          <template #default="{ row, $index }">
            <el-input
              v-model="row.rollerRoughnessStandard"
              @blur="handleInput2(row, $index, 'rollerRoughnessStandard')"
              :style="{ height: '25px' }"
            />
          </template>
        </el-table-column>
        <el-table-column label="公差下限" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
              <span style="color: red; font-weight: 700">*</span>
            </span>
          </template>
          <template #default="{ row, $index }">
            <el-input
              v-model="row.rollerRoughnessToleranceLower"
              :style="{ height: '25px' }"
              @blur="handleInput2(row, $index, 'rollerRoughnessToleranceLower')"
            />
          </template>
        </el-table-column>
        <el-table-column label="公差上限" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
              <span style="color: red; font-weight: 700">*</span>
            </span>
          </template>
          <template #default="{ row, $index }">
            <el-input
              v-model="row.rollerRoughnessToleranceUp"
              :style="{ height: '25px' }"
              @blur="handleInput2(row, $index, 'rollerRoughnessToleranceUp')"
            />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="产品粗糙度" width="240" align="center">
        <el-table-column label="标准" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
              <span style="color: red; font-weight: 700">*</span>
            </span>
          </template>
          <template #default="{ row, $index }">
            <el-input
              v-model="row.productRoughnessStandard"
              @blur="handleInput2(row, $index, 'productRoughnessStandard')"
              :style="{ height: '25px' }"
            />
          </template>
        </el-table-column>
        <el-table-column label="公差下限" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
              <span style="color: red; font-weight: 700">*</span>
            </span>
          </template>
          <template #default="{ row, $index }">
            <el-input
              v-model="row.productRoughnessToleranceLower"
              :style="{ height: '25px' }"
              @blur="handleInput2(row, $index, 'productRoughnessToleranceLower')"
            />
          </template>
        </el-table-column>
        <el-table-column label="公差上限" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
              <span style="color: red; font-weight: 700">*</span>
            </span>
          </template>
          <template #default="{ row, $index }">
            <el-input
              v-model="row.productRoughnessToleranceUp"
              :style="{ height: '25px' }"
              @blur="handleInput2(row, $index, 'productRoughnessToleranceUp')"
            />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="备注" align="left">
        <template #default="{ row, $index }">
          <el-input v-model="row.description" :style="{ height: '25px' }" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="按钮" width="160" align="center" fixed="right">
        <template #default="{ row, $index }">
          <el-button
            :style="{ height: '25px' }"
            type="daprimarynger"
            size="mini"
            @click="addRowTableData3()"
            >增行</el-button
          >
          <el-button
            :style="{ height: '25px' }"
            type="danger"
            size="mini"
            @click="deleteRow3(row)"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>
  </div>
  <el-container>
    <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
      <!-- 头部按钮 -->
      <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
        <div>
          <el-button @click="searchButton" type="primary"> 查询</el-button>
          <el-button @click="openInseart" type="success"> 新增</el-button>
          <el-button @click="handleAudit" type="warning"> 审核</el-button>
          <el-button @click="handleAudit0" type="warning"> 弃审</el-button>
          <el-button @click="deleteButton" type="danger"> 删除</el-button>
        </div>
        <!-- <div class="title">需求汇总统计表</div> -->
      </el-row>
      <div
        style="
          margin-left: 6rem;
          height: 30px;

          background: rgb(241, 244, 243);
          margin-bottom: 0;
          position: relative;
          display: flex;
          justify-content: flex-start;
        "
      >
        <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="inputCode"
          placeholder="结构编号"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input>

        <!-- <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="inputCode"
          placeholder="班组编号"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input> -->
      </div>
    </el-header>
    <el-container>
      <el-container>
        <el-main style="padding: 2px 2px 0 2px; margin-left: 6rem">
          <el-table
            v-loading="loading"
            ref="table"
            :data="tableData"
            border
            stripe
            :cell-style="cellStyle"
            :header-cell-style="headerCellStyle"
            @selection-change="handleSelectionChange"
            @row-dblclick="handleRowClick"
            @row-click="RowClick"
            :row-style="rowState"
            :row-key="(row:any) => row.id"
            :max-height="screenHeight"
            :height="screenHeight"
          >
            <el-table-column fixed type="index" width="80" align="center" />
            <el-table-column fixed type="selection" width="50" align="center" />
            <!-- <el-table-column prop="id" label="ID" width="70" align="center" /> -->
            <!-- <el-table-column
              prop="processCode"
              label="标准编号"
              width="80"
              align="center"
            />
            <el-table-column
              prop="processName"
              label="标准名称"
              width="280"
              align="left"
            /> -->

            <el-table-column prop="name" label="设备零件" width="140" align="center" />1

            <el-table-column
              prop="structureName"
              label="设备结构"
              width="120"
              align="center"
            />
            <!-- <el-table-column
              prop="consumableCategoryName"
              label="耗材类别"
              width="120"
              align="center"
            /> -->
            <el-table-column prop="modelName" label="型号" width="120" align="center" />

            <!-- <el-table-column
              prop="standardType"
              label="标准类型"
              width="120"
              align="center"
            /> -->
            <!-- <el-table-column prop="type" label="类型" width="120" align="center" /> -->
            <el-table-column
              prop="proceduresName"
              label="工序"
              width="120"
              align="center"
            />
            <el-table-column
              prop="processPropertyName"
              label="工序属性"
              width="120"
              align="center"
            />
            <el-table-column
              prop="lowerHardness"
              label="硬度下限"
              width="120"
              align="center"
            />

            <el-table-column
              prop="upHardness"
              label="硬度上限"
              width="120"
              align="center"
            />
            <el-table-column
              prop="lowerPattern"
              label="版型下限"
              width="120"
              align="center"
            />
            <el-table-column
              prop="upPattern"
              label="版型上限"
              width="120"
              align="center"
            />
            <el-table-column
              prop="passToolNumber"
              label="道次总数"
              width="80"
              align="center"
            />
            <el-table-column
              prop="productPurposeName"
              label="产品用途"
              width="80"
              align="center"
            />
            <el-table-column prop="materialName" label="材质" width="80" align="center" />
            <el-table-column prop="creator" label="创建人" width="120" align="center" />
            <el-table-column prop="reviewer" label="审核人" width="120" align="center" />
            <el-table-column prop="modifier" label="修改人" width="120" align="center" />
            <el-table-column
              fixed="right"
              prop="stateName"
              label="状态"
              width="120"
              align="center"
            />
            <el-table-column
              fixed="right"
              prop="explain"
              label="说明"
              width="300"
              align="center"
            />
          </el-table>
        </el-main>
        <el-footer style="height: 20px">
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="page"
              v-model:page-size="limit"
              :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
              :small="true"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-footer>
      </el-container>
    </el-container>
  </el-container>
  <SearchTableDialog
    ref="sed"
    @row-data="handleRowData"
    @row-datas="handleRowDatas"
  ></SearchTableDialog>
  <SearchTableDialog
    ref="sea"
    @row-data="handleRowData1"
    @row-datas="handleRowDatas1"
  ></SearchTableDialog>
  <SearchTableDialog
    ref="seb"
    @row-data="handleRowData2"
    @row-datas="handleRowDatas2"
  ></SearchTableDialog>
</template>
<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  ElTable,
  TableColumnCtx,
  ElMessageBox,
} from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
// crud封装组件
import * as crud from "../../components/utils/crud.ts";
import SearchTableDialog from "@/components/dialogs/SearchTableDialog.vue";
import * as notifications from "../../components/utils/notification.ts";
import Co from "../../components/utils/t-ui-plus-dev/packages/select-table/src/index.vue";

// 时间
// 获取当前时间
const getCurrentFormattedDateTime = () => {
  const currentDateTime = new Date();

  // 格式化当前时间
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  // const formattedDateTime = format(currentDateTime, "YYYY-MM-dd HH:mm:ss");

  return formattedDateTime;
};
// 获取年月日
const getCurrentFormattedDate = () => {
  const currentDateTime = new Date();

  // 格式化当前时间，只获取年月日
  const formattedDate = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formattedDate;
};
// 权限控制
const searchButtonPermissionsA = ref(false);
const menuId = ref(0);
const buttonVariables = {
  searchButtonPermissionsA,
};
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");
  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();
//权限结束
const tableData = ref([]);
const dialogTableVisible1 = ref(false);
const loading = ref(false);
const page = ref(1);
const limit = ref(50);
const total = ref(50);
const inputName = ref("");
const inputCode = ref("");
const selectBusinessDate = computed(() => ({
  page: page.value,
  limit: limit.value,
  equipmentStructure: inputCode.value,
}));
const handleSizeChange = (val: number) => {
  selectBusinessType();
};
const handleCurrentChange = (val: number) => {
  selectBusinessType();
};
const searchButton = () => {
  selectBusinessType();
};
const selectBusinessType = async () => {
  loading.value = true;
  try {
    const res = await crud.fetchData(
      "/Prod/select/ReplaceProcessStandards",
      "post",
      selectBusinessDate.value
    );
    console.log(res);
    if (res.length == 0) {
      total.value = 0;
      tableData.value = [];
      loading.value = false;
      return;
    }
    const definitionsList = res;
    total.value = definitionsList[0].total;
    loading.value = false;

    tableData.value = definitionsList.map((item: any) => ({
      consumableCategoryName:
        item.consumableCategory === 0
          ? "辊轴类"
          : item.consumableCategory === 1
          ? "刀具类"
          : item.consumableCategory === 2
          ? "隔套类"
          : item.consumableCategory === 3
          ? "辊箱"
          : item.consumableCategory === 4
          ? "刀轴"
          : "其他",

      // stateName: item.state == 0 ? "待审核" : item.state == 1 ? "已审核" : "其他",
      stateName: 1,

      ...item,
    }));
  } catch (error) {
    loading.value = false;
    console.error("请求失败:", error);
  }
};
selectBusinessType();
// 表格
const headerCellStyle = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
  // padding: "0 0 0 30px",
};
const rowState = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
    // color: "black",
  };
};
const RowClick = (row, selection) => {
  table.value.toggleRowSelection(row);
};
const handleRowClick = async (row, selection) => {
  dialogTableVisible1.value = true;
  showInsertButton.value = false;
  const res = await crud.fetchData("/Prod/select/ReplaceProcessStandardsId/Id", "post", {
    id: row.id,
  });

  formMainTable.value = { ...formMainTable.value, ...res[0] };
  formMainTable.value.processProperty = res[0].processProperty.toString();
  formMainTable.value.procedures = res[0].procedures.toString();
  tableData1.value = [];
  const replacementCategoryListArray = Object.values(
    res[0].productRollerRoughnessSettingSubList
  );
  tableData1.value = [...tableData1.value, ...replacementCategoryListArray];
  if (formMainTable.value.lowerHardness != "" || formMainTable.value.upHardness != "") {
    formMainTable.value.checkbox1 = true;
  } else {
    formMainTable.value.checkbox1 = false;
  }
  if (formMainTable.value.upHardness != "" || formMainTable.value.lowerPattern != "") {
    formMainTable.value.checkbox2 = true;
  } else {
    formMainTable.value.checkbox1 = false;
  }

  //   const rowData3 = { ...defaultRowData3 };
  //   tableData1.value.push(rowData3);
};

const selectedRows = ref([]);
const table = ref();

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
const handleSelectionChange = (selection: any) => {
  selectedRows.value = selection;
};
const screenHeight = ref(null);
const screenWidth = ref(null);
const childTableHeight = ref(null);

const getScreenHeight = () => {
  childTableHeight.value = `${window.innerHeight}` - 213;
  screenHeight.value = window.innerHeight - 146;
  screenWidth.value = window.innerWidth;
};
getScreenHeight();
const requestDataAsid = computed(() => {
  const userName = Cookies.get("userName");
  const creationTime = getCurrentFormattedDateTime();
  //   const deleteIdList = selectedRows.value.map((row) => row.id);

  return {
    userName: userName,
    creationTime: creationTime,
    //  deleteIdList: deleteIdList,
    deleteIdList: selectedRows.value,
  };
});

const handleAudit = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认审核", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }
      requestDataAsid.value.state = 1;
      const res = await crud.sendRequest(
        "/Prod/update/Sh/GrindingProcessStandardMain",
        "post",
        requestDataAsid.value
      );
      selectBusinessType();
    }
  } catch (error) {
    console.error("审核失败:", error);
  }
};

const handleAudit0 = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认弃审", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }
      requestDataAsid.value.state = 0;
      const res = await crud.sendRequest(
        "/Prod/update/Sh/GrindingProcessStandardMain",
        "post",
        requestDataAsid.value
      );
      selectBusinessType();
    }
  } catch (error) {
    console.error("审核失败:", error);
  }
};
const deleteButton = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认删除", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }

      const res = await crud.sendRequest(
        "/Prod/delete/GrindingProcessStandardMain",
        "post",
        requestDataAsid.value
      );
      selectBusinessType();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const asideListData = ref([]);
const asideList = async () => {
  try {
    const res = await crud.fetchData(
      "/BusinessType/select/BusinessType/All/Auto1",
      "post",
      requestData.value
    );
    asideListData.value = res; // 将结果赋值给 ref
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const getParentIds = (nodeId) => {
  const parentIds = [];
  let currentNode = asideListData.value.find((node) => node.id === nodeId);
  while (currentNode && currentNode.parentID !== null) {
    parentIds.push(currentNode.id);
    currentNode = asideListData.value.find((node) => node.id === currentNode.parentID);
  }
  return parentIds.reverse();
};

// 新增页面展示
const openInseart = async () => {
  isTotalAmount.value = false;
  dialogTableVisible1.value = true;
  showInsertButton.value = true;
  isRepairApplication.value = false;
  tableData1.value = [];
  //   nextTick(() => {
  //     for (let a = 0; a < 21; a++) {
  //       addRow();
  //     }
  //   });
};

interface RuleForm {
  id: string;
  workOrderCode: string;
  grindingProcessStandard: string;
  supplier: string;
  status: true;
  supplierAddress: string;
}
const form = reactive<RuleForm>({
  id: "",
  workOrderCode: "",
  grindingProcessStandard: "",
  supplier: "",
  supplierAddress: "",
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
  // name: [{ message: "请输入班组名称", trigger: "blur"  }],
});
// 子表展示
const cellStyle1 = ({ row, column, rowIndex, columnIndex }) => {
  return { borderColor: "#B9C9C7", padding: "0px", margin: 0 };
};
const showInsertButton = ref(true);
const multipleTableRef = ref();
const handleSelectionChange1 = (val: any[]) => {
  console.log("Selected Rows:", val);
};
// const handleInput = (prop) => {
//   const val = parseFloat(formMainTable.value[prop]);
//   if (!isNaN(val) && isFinite(val)) {
//     formMainTable.value[prop] = formMainTable.value[prop].replace(/\D/g, "");
//     tableData1.value = [];
//     for (let i = 0; i < formMainTable.value.passToolNumber; i++) {
//       addRow();
//     }
//     return;
//   }
//   formMainTable.value[prop] = 0;
//   tableData1.value = [];
// };
const handleInput = (prop) => {
  const val = parseFloat(formMainTable.value[prop]);
  if (!isNaN(val) && isFinite(val)) {
    // 确保输入值是数字，并将非数字字符移除
    formMainTable.value[prop] = formMainTable.value[prop].replace(/\D/g, "");

    // 获取需要的行数
    const passToolNumber = parseInt(formMainTable.value.passToolNumber, 10);

    // 比较当前行数与所需行数
    if (tableData1.value.length > passToolNumber) {
      // 删除多余的行
      tableData1.value.splice(passToolNumber);
    } else if (tableData1.value.length < passToolNumber) {
      // 添加缺少的行
      const diff = passToolNumber - tableData1.value.length;
      for (let i = 0; i < diff; i++) {
        addRow();
      }
    } else {
      // 如果相等，重置并重新添加行
      tableData1.value = [];
      for (let i = 0; i < passToolNumber; i++) {
        addRow();
      }
    }
    return;
  }

  // 如果输入值无效，将其重置为0，并清空表格数据
  formMainTable.value[prop] = 0;
  tableData1.value = [];
};
const handleInput1 = (prop) => {
  const val = parseFloat(formMainTable.value[prop]);
  if (!isNaN(val) && isFinite(val)) {
    //  const roundedVal = val.toFixed(4);
    const roundedVal = val.toString().match(/^-?\d+(\.\d{0,4})?/)[0];
    formMainTable.value[prop] = roundedVal;
    return;
  }
  row[prop] = 0;
};
const handleInput2 = (row, index, prop) => {
  const val = parseFloat(row[prop]);
  if (!isNaN(val) && isFinite(val)) {
    const roundedVal = val.toString().match(/^-?\d+(\.\d{0,4})?/)[0];
    row[prop] = roundedVal;
    return;
  }
  row[prop] = 0;
};
const mainTablePathCount = ref(0);
const defaultRowData = {
  id: "",
  m0Id: "",
  name: "",
  rollerRoughnessStandard: "",
  rollerRoughnessToleranceLower: "",
  rollerRoughnessToleranceUp: "",
  productRoughnessStandard: "",
  productRoughnessToleranceLower: "",
  productRoughnessToleranceUp: "",
  description: "", //备注
};

const tableData1 = ref([
  {
    ...defaultRowData,
  },
  // More data...
]);

const getPassName = (index, total) => {
  if (index === 0) {
    return "第一个道次";
  } else if (index === total - 1) {
    return "成品道次";
  } else if (index === total - 2) {
    return "倒数第二道次";
  } else {
    return `中间道次 ${index}`;
  }
};
const OFFdialogTableVisible = () => {
  dialogTableVisible1.value = false;
  selectBusinessType();
  flushed();
  //   clearForm();
};
// const clearForm = () => {
//   Object.keys(form).forEach((key) => {
//     if (typeof form[key] === "boolean") {
//       Vue.set(form, key, true);
//     } else {
//       Vue.set(form, key, "");
//     }
//   });
// };

const flushed = () => {
  tableData1.value = [];
  isDc.value = false;
  formMainTable.value = { ...initialFormMainTable };
};

// 定义初始值
const initialFormMainTable = {
  id: "",
  processCode: "",
  processName: "",
  standardType: "0", // 标准类型
  state: "", // 状态
  equipmentParts: "", // 设备零件
  name: "", //零件的名称
  equipmentStructure: "", // 设备结构
  structureName: "", //设备名称
  consumableCategory: "", // 耗材类别
  consumableCategoryName: "", //耗材类别名称
  model: "", // 型号
  modelName: "",
  productPurpose: "", // 产品用途ID
  productPurposeName: "", //产品用途名称
  material: "", // 材质
  materialName: "", // 材质名称
  procedures: "", //工序
  processProperty: "1", // 工序属性
  passToolNumber: 0, // 道次/刀数
  standardDetails: "", //标准详述
  cycleMethod: "", // 周期方式
  replacementMethod: "", // 更换方式
  manHourUnit: "0", // 工时单位
  manHourDuration: "", // 工时时长
  lowerHardness: "", //硬度下限
  upHardness: "", //硬度上限
  lowerPattern: "", //版型下限
  upPattern: "", //版型上限
  type: "0", // 类型
  creator: "", //创建者
  creatorID: "", // 创建者ID
  creationTime: "", // 创建时间
  reviewer: "", // 审核者
  reviewerID: "", // 审核者ID
  reviewTime: "", // 审核时间
  modifier: "", // 修改者
  modifierID: "", // 修改者ID
  modificationTime: "", // 修改时间
  explain: "", //说明
  checkbox1: false, //复选框1
  checkbox2: false, //复选框2
};
const addRow = () => {
  tableData1.value.push({ ...defaultRowData });
};
const requestFormTable = computed(() => {
  //  const usefulDataArray = tableData1.value.filter(
  //    (item) => item.cycleLength != "" || item.cycleLength != 0
  const usefulDataArray = tableData1.value;

  const formMainTableDate = formMainTable.value;
  const userName = Cookies.get("userName");
  const creationTime: creationTime = getCurrentFormattedDateTime();
  return {
    userName: userName,
    creationTime: creationTime,
    childList: usefulDataArray,
    formMainTable: formMainTableDate,
  };
});
//必填验证
const isTrue = ref(true);
const isRole = () => {
  isTrue.value = true;

  isTrue.value = false;
};

const updateMaterialsFixed = async () => {
  const res = await crud.sendRequest(
    "/Prod/update/GrindingProcessStandardMain/",
    "post",
    requestFormTable.value
  );
  OFFdialogTableVisible();
};

const getAllData = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认保存", "success");
    //  console.log(requestFormTable.value);
    if (!result) {
      // 用户点击了取消按钮，不执行保存操作
      return;
    }
    await isRole();

    if (isTrue.value) {
      return;
    }
    const res = await crud.sendRequest(
      "/Prod/add/ReplaceProcessStandards",
      "post",
      requestFormTable.value
    );

    if (res.code == 200) {
      OFFdialogTableVisible();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const getSelectedData = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
};

const deleteSelectedRows = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
  selectedRows.forEach((row) => {
    const index = tableData1.value.indexOf(row);
    if (index !== -1) {
      tableData1.value.splice(index, 1);
    }
  });
};

const deleteRow = (row: any) => {
  const index = tableData1.value.indexOf(row);
  if (index !== -1) {
    tableData1.value.splice(index, 1);
  }
};
const headerCellStyle1 = {
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA",
  fontWeight: "bold",
  color: "#1F2129",
  height: "40px",
  margin: 0,
  padding: 0,
};
// 弹窗
const indexEmployeeJob = ref(0);
const isRepairApplication = ref(false);
const isdisRepairApplication = ref(false);
const isTotalAmount = ref(true);
const flushed1 = async (value) => {
  formMainTable.value.workTeam = "";
  formMainTable.value.name = "";
  formMainTable.value.repairTime = "";
  formMainTable.value.repairTimeUnit = "";
  formMainTable.value.supplier = "";
  formMainTable.value.supplierAddress = "";
};
const handleValueRangeChange = async (value) => {
  flushed1();
  let repairMode = formMainTable.value.repairMode;
  if (repairMode == "0") {
    isRepairApplication.value = false;
    isdisRepairApplication.value = false;
  } else {
    isRepairApplication.value = true;
    isdisRepairApplication.value = true;
  }
};
const sed = ref<any>(null);
const sea = ref<any>(null);
const seb = ref<any>(null);
const openEqipmentParts = async () => {
  sed.value.dialogTableVisible = true;
  openDial();
};
const openEqipmentParts1 = async () => {
  sea.value.dialogTableVisible = true;
  openDial1();
};
const openEqipmentParts2 = async () => {
  seb.value.dialogTableVisible = true;
  openDial2();
};
const tableDemo = ref([
  { type: "index", fixed: true, width: "60", align: "center" },
  //   { type: "selection", width: "65", align: "center" },
  { prop: "structureName", label: "结构名称", width: "120", align: "center" },
  { prop: "name", label: "设备零件", width: "150", align: "center" },
  { prop: "model", label: "型号", width: "150", align: "center" },
  { prop: "consumableCategoryName", label: "耗材类别", width: "120", align: "center" },
]);
const tableDemo1 = ref([
  { type: "index", fixed: true, width: "60", align: "center" },
  //   { type: "selection", width: "65", align: "center" },
  { prop: "ytbm", label: "编码", width: "120", align: "center" },
  { prop: "ytfl", label: "分类", width: "120", align: "center" },
  { prop: "ytmc", label: "用途", width: "150", align: "center" },
  { prop: "remark", label: "备注", width: "150", align: "center" },
]);

const openDial = () => {
  sed.value.ifRowChoose = false;
  sed.value.ifdynamic1 = true;
  sed.value.ifdynamic2 = true;
  sed.value.dynamicPlaceholder1 = "零件名称";
  sed.value.dynamicPlaceholder2 = "结构名称";
  sed.value.ifdynamic3 = false;
  sed.value.tableColumns = tableDemo.value;
  sed.value.apiUrl = "/CoInformation/select/ComponentBasicInformation";
  sed.value.searchInput();
};
const openDial1 = () => {
  sea.value.ifRowChoose = false;
  sea.value.ifdynamic1 = true;
  sea.value.ifdynamic2 = true;
  sea.value.ifdynamic3 = true;
  sea.value.dynamicPlaceholder1 = "用途编码";
  sea.value.dynamicPlaceholder2 = "用途分类";
  sea.value.dynamicPlaceholder3 = "用途名称";
  sea.value.tableColumns = tableDemo1.value;
  sea.value.apiUrl = "/Material/Select/UseDefinition/Mc";
  sea.value.searchInput();
};
const openDial2 = () => {
  seb.value.ifRowChoose = false;
  seb.value.ifdynamic1 = true;
  seb.value.ifdynamic2 = true;
  seb.value.ifdynamic3 = true;
  seb.value.dynamicPlaceholder1 = "材质编码";
  seb.value.dynamicPlaceholder2 = "材质分类";
  seb.value.dynamicPlaceholder3 = "材质名称";
  seb.value.tableColumns = tableDemo1.value;
  seb.value.apiUrl = "/Mat/Select/UseDefinition/Mc";
  seb.value.searchInput();
};

// const flushed1 = () => {
//   tableData1.value = [];
//   for (let a = 0; a < 21; a++) {
//     addRow();
//   }
// };

const handleRowData = async (row) => {
  //名称
  formMainTable.value.consumableCategoryName = row.consumableCategoryName;
  formMainTable.value.name = row.name;
  formMainTable.value.structureName = row.structureName;
  //id
  //设备零件id componentId
  formMainTable.value.equipmentParts = row.componentId;
  formMainTable.value.equipmentStructure = row.structureCode;
  formMainTable.value.consumableCategory = row.consumableCategory;
  formMainTable.value.model = row.id;
  formMainTable.value.modelName = row.model;
};

const handleRowData1 = async (row) => {
  formMainTable.value.productPurpose = row.id;
  formMainTable.value.productPurposeName = row.ytmc;
};
const handleRowData2 = async (row) => {
  formMainTable.value.material = row.id;
  formMainTable.value.materialName = row.ytmc;
};
//周期方式
const isTypeDisabled = ref(true);
const typeOptions = ref([]);
const columnLabel = ref("道次序号");
const isDc = ref(false);
const handleReplacementMethodChange = () => {
  isTypeDisabled.value = false;
  formMainTable.value.cycleMethod = "";
  typeOptions.value = [];
  tableData1.value = [];
  //   for (let i = 0; i < 5; i++) {
  //     const rowData1 = { ...defaultRowData };
  //     tableData1.value.push(rowData1);
  //   }
  const rowData1 = { ...defaultRowData };
  if (
    formMainTable.value.replacementMethod == "0" ||
    formMainTable.value.replacementMethod == "2"
  ) {
    tableData1.value.push(rowData1);
    isDc.value = false;
    formMainTable.value.passToolNumber = 0;
  } else {
    let iList = parseInt(formMainTable.value.passToolNumber, 10);
    isDc.value = true;
    console.log(isDc);
    for (let i = 0; i < iList; i++) {
      tableData1.value.push(rowData1);
    }
  }
  updateTypeOptions();
};
const updateTypeOptions = () => {
  const replacementMethod = formMainTable.value.replacementMethod;
  // 根据不同的更换方式设置不同的类型选项
  if (replacementMethod === "0") {
    typeOptions.value = [
      { label: "天数", value: "0" },
      { label: "小时", value: "1" },
      { label: "分钟", value: "2" },
    ];
    return;
  }
  if (replacementMethod === "1") {
    if (formMainTable.value.consumableCategory == 0) {
      typeOptions.value = [{ label: "道次", value: "3" }];
      return;
    }
    if (formMainTable.value.consumableCategory == 1) {
      typeOptions.value = [{ label: "刀次", value: "4" }];
      return;
    }
    typeOptions.value = [{ label: "次", value: "5" }];
    return;
  }
  if (replacementMethod === "2") {
    typeOptions.value = [{ label: "产量", value: "6" }];
    return;
  }

  typeOptions.value = [];
};

const clickOrganizationSelect = () => {};
const openprocessProperty = async () => {
  if (
    formMainTable.value.processProperty == "1" ||
    formMainTable.value.processProperty == "3"
  ) {
    tableData1.value.forEach((row) => {
      // console.log(row);
      row.processProperty = "0";
    });
  }
  if (
    formMainTable.value.processProperty == "2" ||
    formMainTable.value.processProperty == "4"
  ) {
    tableData1.value.forEach((row) => {
      row.processProperty = "1";
    });
  }
  if (formMainTable.value.processProperty == "5") {
    tableData1.value.forEach((row) => {
      row.processProperty = "2";
    });
  }
};
// 定义前端数据模型
const formMainTable = ref({
  id: "",
  processCode: "",
  processName: "",
  standardType: "0", // 标准类型
  equipmentParts: "", // 设备零件
  name: "", //零件的名称
  equipmentStructure: "", // 设备结构
  structureName: "", //设备名称
  consumableCategory: "", // 耗材类别
  consumableCategoryName: "", //耗材类别名称
  model: "", // 型号
  modelName: "",
  productPurpose: "", // 产品用途ID
  productPurposeName: "", //产品用途名称
  material: "", // 材质
  materialName: "", // 材质名称
  procedures: "", //工序
  processProperty: "1", // 工序属性
  passToolNumber: 0, // 道次/刀数
  standardDetails: "", //标准详述
  cycleMethod: "", // 周期方式
  replacementMethod: "", // 更换方式
  manHourUnit: "0", // 工时单位
  manHourDuration: "", // 工时时长
  type: "0", // 类型
  lowerHardness: "", //硬度下限
  upHardness: "", //硬度上限
  lowerPattern: "", //版型下限
  upPattern: "", //版型上限
  creator: "", //创建者
  creatorID: "", // 创建者ID
  creationTime: "", // 创建时间
  reviewer: "", // 审核者
  reviewerID: "", // 审核者ID
  reviewTime: "", // 审核时间
  modifier: "", // 修改者
  modifierID: "", // 修改者ID
  modificationTime: "", // 修改时间
  explain: "", //说明
  state: "", // 状态
  checkbox1: false, //复选框1
  checkbox2: false, //复选框2
});
const addRowTableData3 = () => {
  tableData1.value.push({
    ...defaultRowData,
  });
};
const deleteRow3 = (row: any) => {
  const index = tableData1.value.indexOf(row);
  if (index != -1) {
    tableData1.value.splice(index, 1);
  }
};
const handleInput3 = (row, index, prop) => {
  if (prop == "cycleLength") {
    if (
      formMainTable.value.replacementMethod == 0 ||
      formMainTable.value.replacementMethod == 2
    ) {
      const val = parseFloat(row[prop]);
      if (!isNaN(val) && isFinite(val)) {
        //   const roundedVal = val.toFixed(4);
        const roundedVal = val.toString().match(/^-?\d+(\.\d{0,4})?/)[0];
        row[prop] = roundedVal;
      } else {
        row[prop] = 0;
      }
    }
    if (formMainTable.value.replacementMethod == 1) {
      if (row[prop] == "") {
        row[prop] = 0;
      } else {
        row[prop] = row[prop].replace(/\D/g, "");
      }
    }
  } else {
    const val = parseFloat(row[prop]);
    if (!isNaN(val) && isFinite(val)) {
      // const roundedVal = val.toFixed(4);
      const roundedVal = val.toString().match(/^-?\d+(\.\d{0,4})?/)[0];
      row[prop] = roundedVal;
    } else {
      row[prop] = 0;
    }
  }

  if (
    row.cycleUnitOutput != "" &&
    row.cycleLength != "" &&
    row.cycleUnitOutput != 0 &&
    row.cycleLength != 0
  ) {
    const unitOutput = parseFloat(row.cycleUnitOutput);
    const cycleLength = parseFloat(row.cycleLength);
    const cycleOutput = unitOutput * cycleLength;
    //  row.cycleOutput = cycleOutput.toFixed(4);
    row.cycleOutput = cycleOutput.toString().match(/^-?\d+(\.\d{0,4})?/)[0];
  }
};
const handleCheckBox1 = async () => {};
const handleCheckBox2 = async () => {};
</script>
<style scoped>
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.down-tree ::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
  display: inline;
}

.down-tree {
  height: 100%;
}

.demo-pagination-block {
  float: right;
}

.custom-dialog {
  position: fixed;
  top: 10em;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.labs {
  margin-bottom: 0px;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}
</style>
